/***************************************************************************
 *   Copyright (C) 2007 by Autostop team                                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include <stdio.h>

#include <QImage>
#include <QFileInfo>

#include <analyzer.h>

int main( int argc, char** argv )
{
	// get input handle and output filename
	FILE* input = stdin;
	QString outFile = "out.png";
	
	if ( argc > 1 )
	{
		input = fopen( argv[1], "rb" ); // note "b", Windows (TM) compatibility :)
		if ( !input )
		{
			perror("Could not open input file");
			return 1;
		}
		outFile = QFileInfo(argv[1]).baseName() + QString(".png");
	}
	
	// load image
	pimage_t pImage = load_image( input );
	if ( ! pImage )
	{
		fprintf( stderr, "Error loading image" );
		return 2;
	}
	
	// find max value
	int maxValue = 0;
	foreach_pixel( pPixel, pImage )
	{
		if ( *pPixel > maxValue)
		{
			maxValue = *pPixel;
		}
	}
	
	// convert to QIMage
	QImage output( pImage->width, pImage->height, QImage::Format_RGB32 );
	
	for( int y = 0; y < pImage->height; y++ )
	{
		for( int x = 0; x < pImage->width; x++ )
		{
			int value = image_pixel( pImage, x, y );
			// scale value
			if ( maxValue > 0 )
			{
				value = 255.0 * value / maxValue;
			}
			output.setPixel( x, y, qRgb( value, value, value ) );
		}
	}
	
	if ( output.save( outFile ) )
	{
		fprintf( stderr, "Saved to %s\n", qPrintable( outFile ) );
		return 0;
	}
	
	fprintf( stderr, "Error saving to %s\n", qPrintable( outFile ) );
	return 3;
}


// eof

